package com.ct.gd.passport.view;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;

import com.ct.gd.passport.R;
import com.ct.gd.passport.common.constants.Config;
import com.ct.gd.passport.common.constants.Config.Area;
import com.umeng.analytics.MobclickAgent;
import com.up91.common.android.async.ILoading;
import com.up91.common.android.async.SimpleAsyncTask;
import com.up91.common.android.view.adapter.SimpleListAdapter;

public class LocationFragment extends Fragment implements OnItemClickListener, OnClickListener, OnDismissListener {
	private static final int				POPUP_WIDTH					= 320;

	private Set<OnLocationChangedListener>	mOnLocationChangedListeners	= new LinkedHashSet<LocationFragment.OnLocationChangedListener>();
	private Set<OnLocationsLoadedListener>	mOnLocationsLoadedListeners	= new LinkedHashSet<LocationFragment.OnLocationsLoadedListener>();

	private TextView						mTVLocation;
	private ListView						mLVLocation;
	private LocationListAdapter				mLocationAdapter;

	private PopupWindow						mPwLocations;

	public interface OnLocationChangedListener {
		void onLocationChanged(Area area);
	}

	public interface OnLocationsLoadedListener {
		void onLocationsLoaded(List<Area> areas);
	}

	private void notifyOnLocationChanged(Area area) {
		Config.currentArea = area;
		for (OnLocationChangedListener listener : mOnLocationChangedListeners) {
			listener.onLocationChanged(area);
		}
	}

	private void notifyOnLocationsLoaded(List<Area> areas) {
		for (OnLocationsLoadedListener listener : mOnLocationsLoadedListeners) {
			listener.onLocationsLoaded(areas);
		}
	}

	public boolean registerOnLocationChangedListener(OnLocationChangedListener listener) {
		return mOnLocationChangedListeners.add(listener);
	}

	public boolean unregisterOnLocationChangedListener(OnLocationChangedListener listener) {
		return mOnLocationChangedListeners.remove(listener);
	}

	public boolean registerOnLocationsLoadedListener(OnLocationsLoadedListener listener) {
		return mOnLocationsLoadedListeners.add(listener);
	}

	public boolean unregisterOnLocationsLoadedListener(OnLocationsLoadedListener listener) {
		return mOnLocationsLoadedListeners.remove(listener);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		loadLocations();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.customheader_center, null);
		mTVLocation = (TextView) v.findViewById(R.id.tv_header_center);
		// mTVLocation.setText(R.string.travelAssist_switch_button);
		mTVLocation.setOnClickListener(this);

		// v.setVisibility(View.INVISIBLE);

		mLVLocation = (ListView) inflater.inflate(R.layout.bank_type, null);
		mLocationAdapter = new LocationListAdapter(getActivity(), null);
		mLVLocation.setAdapter(mLocationAdapter);
		mLVLocation.setItemsCanFocus(false);
		mLVLocation.setOnItemClickListener(this);
		mTVLocation.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_down, 0);
		return v;
	}

	public TextView getLocationTextView() {
		return mTVLocation;
	}

	private PopupWindow createPopupWindow() {
		PopupWindow pw = new PopupWindow(mLVLocation, POPUP_WIDTH, ViewGroup.LayoutParams.WRAP_CONTENT);
		pw.setBackgroundDrawable(getResources().getDrawable(android.R.color.white));
		pw.setOutsideTouchable(true);
		pw.setTouchable(true);
		pw.setFocusable(true);
		return pw;
	}

	@Override
	public void onClick(View v) {
		// 切换按钮
		if (mPwLocations == null) {
			mPwLocations = createPopupWindow();
			mPwLocations.setOnDismissListener(this);
		}

		if (!mPwLocations.isShowing()) {
			mPwLocations.showAtLocation(v, Gravity.LEFT | Gravity.TOP, computePopupWindowXOffset(), computePopupWindowYOffset());
			mTVLocation.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_up, 0);
		}
		else mPwLocations.dismiss();
	}

	@Override
	public void onDismiss() {
		mTVLocation.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_down, 0);
	}

	private int computePopupWindowXOffset() {
		Display display = getActivity().getWindowManager().getDefaultDisplay();
		int width = display.getWidth(); // deprecated
		int result = (width - mPwLocations.getWidth()) / 2;
//		ToastHelper.toast(getActivity(), ":" + result);
		return result;
	}

	private int computePopupWindowYOffset() {
		Rect rectgle = new Rect();
		getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(rectgle);
		int notificationHeight = rectgle.top;
		
//		Display display = getActivity().getWindowManager().getDefaultDisplay();
//		int heigth = display.getHeight(); // deprecated
//		int result = heigth - mTVLocation.getBottom();
		int result = mTVLocation.getBottom();
		return notificationHeight + result;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Area location = (Area) parent.getItemAtPosition(position);
		MobclickAgent.onEvent(getActivity(), location.eventId);
		notifyOnLocationChanged(location);
		mPwLocations.dismiss();
	}

	private static class LocationListAdapter extends SimpleListAdapter<Area> {
		private class ViewHolder {
			TextView	tvTitle;
		}

		public LocationListAdapter(Context context, List<Area> data) {
			super(context, data);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = new ViewHolder();
			if (null == convertView) {
				convertView = mInflater.inflate(R.layout.bank_type_list_item, null);
				holder.tvTitle = (TextView) convertView.findViewById(R.id.tv_bank_type_name);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			Area area = (Area) getItem(position);
			holder.tvTitle.setText(area.name);
			return convertView;
		}
	}

	void loadLocations() {
		if (null != getActivity()) new QueryLocationTask((ILoading) getActivity()).execute();
	}

	private class QueryLocationTask extends SimpleAsyncTask<Void, Void, List<Area>> {

		public QueryLocationTask(ILoading context) {
			super(context);
		}

		@Override
		protected List<Area> onLoad(Void... params) {
			ArrayList<Area> result = new ArrayList<Area>();
			for (Area area : Area.values()) {
				result.add(area);
			}
			return result;
		}

		@Override
		protected void onUI(List<Area> result) {
			mLocationAdapter.setData(result);
			mLocationAdapter.notifyDataSetChanged();

			notifyOnLocationsLoaded(result);

			if (1 == result.size()) {
				((ViewGroup) getView()).getChildAt(0).setVisibility(View.INVISIBLE);
				notifyOnLocationChanged(result.get(0));
			} else {
				((ViewGroup) getView()).getChildAt(0).setVisibility(View.VISIBLE);

				// 如果未选题库则默认选中第一项
				if (AdapterView.INVALID_POSITION == mLVLocation.getCheckedItemPosition()) {
					mLVLocation.setItemChecked(0, true);
					notifyOnLocationChanged(result.get(0));
				}
			}
		}
	}

//	public static class Location {
//		private static Location	sCurrLocation;
//
//		public static void setCurrLocation(Location bankType) {
//			sCurrLocation = bankType;
//		}
//
//		public static Location getCurrLocation() {
//			return sCurrLocation;
//		}
//
//		public static List<Location> load() {
//			ArrayList<Location> result = new ArrayList<Location>();
//			result.add(new Location(0, "香港"));
//			result.add(new Location(1, "澳门"));
//			return result;
//		}
//
//		private int		code;
//		private String	name;
//
//		public Location(int code, String name) {
//			super();
//			this.code = code;
//			this.name = name;
//		}
//
//		public int getCode() {
//			return code;
//		}
//
//		public String getName() {
//			return name;
//		}
//	}
}
